package main

import (
	"eco/shell/util"
	"fmt"
	"github.com/fatih/color"
	"github.com/urfave/cli"
	"os"
)

// test yaml
func main() {
	conf, _ := util.ReadYamlConfig("./server.yaml")
	app := cli.NewApp()
	app.Name = "eco_tools"
	app.Usage = "Eco deployment Toolkit"
	app.Version = "v1.0.0"
	app.Commands = []cli.Command{
		{
			Name:  "cmd",
			Usage: "Batch execute commands, eg: cmd \"echo Hi\"",
			Action: func(c *cli.Context) error {
				cmd := c.Args().First()
				for _, val := range conf.Server {
					cmdHandle(val, cmd)
				}
				return nil
			},
		},
		{
			Name:  "scp",
			Usage: "Send file, eg: scp param1<localFile> param2<remoteFile>",
			Action: func(c *cli.Context) error {
				localFile := c.Args().Get(0)
				remoteFile := c.Args().Get(1)
				for _, val := range conf.Server {
					scpHandle(val, localFile, remoteFile)
				}
				return nil
			},
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		panic("agent cli err: " + err.Error())
	}
}

func cmdHandle(server util.Server, cmd string) {
	if cmd == "" {
		cmd = "echo Hi eco tools"
	}
	colNode := color.New(color.FgGreen, color.Bold)
	colNode.Printf("exec node -> %v \n", server)
	xSsh := util.NewXSsh(server.Ip, server.User, server.Psw, server.Port)
	rst, err := xSsh.Run(cmd)
	checkErr(err)
	fmt.Printf("%s \n", rst)
}

func scpHandle(server util.Server, localFile, remoteFile string) {
	if localFile == "" || remoteFile == "" {
		fmt.Println("params is nil")
		return
	}
	colNode := color.New(color.FgGreen, color.Bold)
	colNode.Printf("exec node -> %v localFile: %s, remoteFile:%s \n", server, localFile, remoteFile)
	xSsh := util.NewXSsh(server.Ip, server.User, server.Psw, server.Port)
	rst, err := xSsh.Scp(localFile, remoteFile)
	checkErr(err)
	fmt.Printf("%d \n", rst)
}

func checkErr(err error) {
	if err != nil {
		fmt.Printf("%v \n", err)
	}
}
